var QuestionObjects={};
function Questions(id, DataMethodType, DataMethodName)
{
	QuestionObjects[id] = this;
	this.TableCss = 'QuestionTable';
	this.LabelCss = 'QuestionText';
	this.AnswerCss = 'QuestionAnswer';
	
    this.QuestionData=null;
    this.NoData='No Data.';
    this.OptionWidth=null;
    this.Validators=new Object();
    
    var Content=el(id+'_Content');
    var o=this;
    var FailureImg = ImageUrl('Failure.gif');
    this.ExpandPad = 5;

    this.GetData=function()
    {
        var request=new Object();
        request.DataMethodType=DataMethodType;
        request.DataMethodName=DataMethodName;
        var qi=new Object();
        qi.Parameters=this.Parameters;
        qi.QuestionData=this.GetQuestionData();
        request.QuestionInfo=qi;
        ShowLoading(Content);
        Web.Ajax.Controls.Questions.GetData(request, this.SetData);
    }
    this.SetData = function(r)
    {
    	o.QuestionData = r.Data;
    	if (r.OnComplete)
    		eval(r.OnComplete);
    	o.Render(r.Message);
    	o.Action = 'None';
    }
    this.Validate = function()
    {
    	this.Action = 'Validate';
    	this.GetData();
    } 
    this.GetQuestionId=function(i)
    {
        return (id+'_q_'+i);
    }
    this.GetValidatorId=function(q,i)
    {
        return (id+'_v_'+i);
    }
    this.GetQuestionIndex=function(id)
    {
        var qd=this.QuestionData;
        if(!qd)
            return null;
        for(var i=0;i<qd.length;i++)
        {
            if(qd[i].Id==id)
                return i;
        }
        return null;
    }
    this.GetQuestionById=function(id)
    {
        var qd=this.QuestionData;
        if(!qd)
            return null;
        var idx=this.GetQuestionIndex(id);
        if(idx)
            return qd[idx];
        return null;
    }
    this.GetQuestionByText = function(t)
    {
		var qd = this.QuestionData;
		if (!qd)
			return null;
		for (var i = 0; i < qd.length; i++)
		{
			if (qd[i].Text == t)
				return qd[i];
		}
		return null;
	}
    this.GetQuestionElement=function(id)
    {
        var e=null;
        var idx=this.GetQuestionIndex(id);
        if(idx)
            e=el(this.GetQuestionId(idx));
        return e;
    }
    this.AnswerChanged = function(idx)
    {
    	var q = this.QuestionData[idx];
    	if (!q)
    		return;
    	this.UpdateQuestionData(q, idx);
    	var disable = true;
    	if (!q.EnableDependentsAnswers)
    		return;
    	for (var i = 0; i < q.EnableDependentsAnswers.length; i++)
    	{
    		var sans = '' + q.Answer
    		if (disable && (sans == q.EnableDependentsAnswers[i]))
    			disable = false;
    	}
    	if (!q.DependentQuestionIds)
    		return;
    	for (var i = 0; i < q.DependentQuestionIds.length; i++)
    	{
    		var e = this.GetQuestionElement(q.DependentQuestionIds[i]);
    		if (e)
    		{
    			disable?(e.className+=' disabled'):(e.className=e.className.replace('disabled',''));
    			e.disabled = disable;
    		} 
    		var dq = this.GetQuestionById(q.DependentQuestionIds[i]);
    		if (dq)
    			dq.Enabled = !disable;
    	}
    }
    this.RenderOnChange = function(q, i)
    {
    	var html = '';
    	if (q.DependentQuestionIds)
    	{
    		var event = 'onchange';
    		if (q.Type == 'Bool')
    			event = 'onclick';
    		html += event+'="QuestionObjects[\'' + id + '\'].AnswerChanged(' + i + ');"';
    	}
    	return html;
    }
    this.RenderAnswer = function(q, i) {
    	var html = '';
    	var qid = this.GetQuestionId(i);
    	if (q.Readonly)
    		return '<span>' + q.Answer + '</span>';
    	if (q.Type == 'Bool') {
    		html += '<input ' + this.RenderOnChange(q, i) + ' id="' + qid + '" type="checkbox" ' + ((q.Answer == 'true') ? 'checked' : '') + ' class="QuestionCheckBox" />'
    	}
    	else if (q.Type == 'Options') {
    		var style = '';
    		if (this.OptionWidth)
    			style = 'style="width:' + this.OptionWidth + '"'
    		html += '<select ' + style + ' ' + this.RenderOnChange(q, i) + ' ' + (q.Max == 1 ? '' : 'multiple') + ' id="' + qid + '">';
    		if (q.Options) {
    			html += '<option>Select...</option>';
    			for (var i = 0; i < q.Options.length; i++) {
    				var opt = q.Options[i];
    				var selected = false;
    				if (q.Answer == opt)
    					selected = true;
    				html += '<option value="' + q.Options[i] + '" ' + (selected ? 'selected' : '') + '>' + q.Options[i] + '</option>';
    			}
    		}
    		html += '</select>';
    	}
    	else if (q.Type == 'TextArea') {
    		html += '<textarea ' + this.RenderOnChange(q, i) + ' id="' + qid + '" class="QuestionTextBox" >' + (q.Answer ? q.Answer : '') + '</textarea>';
    	}
    	else if (q.Type == 'DateTime') {
    		var c = new Calendar(qid,0, 0, 'b');
    		window[qid] = c;
    		c.Required = q.Required;
    		q.Control = c;
    		if(q.Answer&&q.Answer!='')
    			try{c.Date = eval('('+q.Answer+')')}catch(e){};
    		return c.GetClientHtml();
    	}
    	else {
    		html += '<input ' + this.RenderOnChange(q, i) + ' id="' + qid + '" type="text" value="' + (q.Answer ? q.Answer : '') + '" class="QuestionTextBox" />'
    	}
    	return html;
    }
    this.RenderValidator=function(q,i)
    {
        var vid=this.GetValidatorId(q,i);
        //var html='<span id="'+vid+'" title="'+(q.ErrorMessage?q.ErrorMessage:'')+'" class="QuestionValidator">*</span>';
        var html=ImageHtml(FailureImg,'QuestionValidator',null,(q.ErrorMessage?q.ErrorMessage:''),vid);
        return html;
    }
    this.RenderQuestion=function(q,i)
    {
    	var html = '<tr>';
    	html += '<td class="' + this.LabelCss + '">' + q.Text + ':&nbsp;</td>';        
        html+='<td class="'+this.AnswerCss+'">'+this.RenderAnswer(q,i)+'&nbsp;'+this.RenderValidator(q,i)+'</td>';  
        html+='</tr>';
        return html;        
    }
    this.Render = function(m) {
    	var d = this.QuestionData;
    	var html = '';
    	if (m)
    		html = '<div class="Error">' + m + '</div>'
    	else {
    		if (!d || d.length == 0)
    			html = '<div class="NoData">' + this.NoData + '</div>'
    		else {
    			html += '<table cellspacing="0" class="' + this.TableCss + '">';
    			for (var i = 0; i < d.length; i++) {
    				if (d[i].Visible)
    					html += this.RenderQuestion(d[i], i);
    			}
    			html += '</table>';
    		}
    	}
    	Content.innerHTML = html;
    	if (this.QuestionData) {
    		for (var i = 0; i < this.QuestionData.length; i++) {
    			var q = this.QuestionData[i];
    			this.AnswerChanged(i);
    			if (q.Control && q.Control.Init)
    				q.Control.Init();
    		}
    	}
    }
    this.Clear=function()
    {
        this.QuestionData=null;
        this.Render();        
    }
    this.UpdateQuestionData = function(q, i) {
    	if (!q.Visible)
    		return;
    	if (q.Type == 'DateTime') {
    		q.Answer = ToJson(q.Control.Date);
    		return;
    	}
    	var qid = this.GetQuestionId(i);
    	var qe = el(qid);
    	if (!qe) return;
    	var ans;
    	if (q.Type == 'Bool')
    		ans = qe.checked;
    	else if (q.Type == 'Options') {
    		ans = '';
    		for (var i = 0; i < qe.options.length; i++) {
    			if (qe.options[i].selected) {
    				if (ans != '') ans += ',';
    				ans += qe.options[i].value;
    			}
    		}
    	}
    	else
    		ans = qe.value;
    	q.Answer = ans;
    }
	this.GetQuestionData=function()
	{
        var d=this.QuestionData;
	    if(d)
	        for(var i=0;i<d.length;i++)
	            this.UpdateQuestionData(d[i],i);
	    return d;
	}
	this.ValidateQuestion=function(q,i)
	{
	    var val=true;
	    if(!q.Visible)
	        return true;
	    var qid=this.GetQuestionId(i);
	    var vid=this.GetValidatorId(q,i);
	    var v=this.Validators[vid];
	    if(v==null)
	    {	        
	        this.Validators[vid]=new Validator(vid,false);
	        v=this.Validators[vid];
	        v.SourceId=qid;
        }
        v.Hide();
        
	    if(!q.Enabled)
	        return true;
	    var m=q.ErrorMessage?q.ErrorMessage:'Validation Error';
	    if(q.Required)
	    {
	        if(q.Answer==null||q.Answer==''||q.Answer=='Select...')
	        {	        
	            val=false;
	            m='This is a required field.'
	        }
	    }
	    if(q.RegEx)
	    {
	        if(q.Answer&&q.Answer!='')
	            val=q.Answer.match(eval(Validator.TranslateRegex(q.RegEx)));
	    }
		// added as emeregency fix by LT
	    if(val && q.Text == 'UAN' && !this.ValidateEircomUAN(q.Answer))
	    {
			val = false;
			m = 'Invalid eircom UAN';
		}
	    if(!val)
	    {
	        v.Show(m);
	    }
	    return val;	    	    
	}
	this.Validate=function()
	{
	    var val=true;
	    var d=this.GetQuestionData();
	    if(d)
	    {
	        for(var i=0;i<d.length;i++)
	        {
	            val=(this.ValidateQuestion(d[i],i)&&val);
	        }
	    }	    
	    return val;
	}
	this.HideValidators=function()
	{
		for (var p in this.Validators)
			this.Validators[p].Hide();
	}
	this.GetExpandPad = function()
	{
		return this.ExpandPad+(Web.Ajax.Browser.indexOf('IE')>-1?5:0);
	}
	this.Expand = function(force)
	{
		var e = el(id);
		var ds = GetDocSize();
		var rec = GetRec(e);
		var nh;
		if (((rec.y + rec.h) < ds.h) || force)
			nh = (ds.h - rec.y - this.GetExpandPad());
		if (nh)
			e.style.height = nh + 'px';
	}
	/// <summary>
	/// Validates an eircom account number using eircom's algorithm.
	/// </summary>
	/// <param name="UAN">The submitted eircom account number.</param>
	/// <returns>True for a valid UAN, false for invalid.</returns>
	this.ValidateEircomUAN=function(UAN)
	{
		if(UAN.length != 8)
			return (false);

		var iUAN = UAN;
		var one = 0, two = 0, three = 0, four = 0, five = 0, six = 0, seven = 0, eight = 0, Sum = 0, Diff = 0;

		one		= iUAN.charAt(0);
		two		= iUAN.charAt(1);
		three	= iUAN.charAt(2);
		four	= iUAN.charAt(3);
		five	= iUAN.charAt(4);
		six		= iUAN.charAt(5);
		seven	= iUAN.charAt(6);
		eight	= iUAN.charAt(7);

		Sum		= ((1 * one) + (2 * two) + (3 * three) + (4 * four) + (5 * five) + (10 * six) + (9 * seven));
		Diff	= (((Math.floor(Sum / 11) + 1) * 11) - Sum);

		if (Diff > 9)
			Diff = 0;
		if (eight != Diff )
			return (false);
		else
			return (true);
	}
}
Questions.prototype=new AjaxControl();

